package com.luoying.itew.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.TextOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.district.DistrictItem;
import com.amap.api.services.district.DistrictResult;
import com.amap.api.services.district.DistrictSearch;
import com.amap.api.services.district.DistrictSearchQuery;
import com.luoying.itew.R;
import com.luoying.itew.bean.DistrictBean;
import com.luoying.itew.bean.MonitorBean;
import com.luoying.itew.bean.StreetBean;
import com.luoying.itew.common.Constant;
import com.luoying.itew.dialog.PointsListDialog;
import com.luoying.itew.manage.UserManage;
import com.luoying.itew.util.AppUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

public class DistrictMapActivity extends BaseActivity implements View.OnClickListener,
        AMap.OnMarkerClickListener, AMap.OnMapClickListener {
    private static final String TAG = "DistrictMapActivity";
    /**
     * 深圳市城市码
     */
    private static final String CITY_CODE = "0755";
    /**
     * 汕尾市城市码
     * 这里指深汕合作新区
     */
    private static final String CITY_CODE_SHAN = "0660";
    //监测点详情
    private RelativeLayout mMarkerInfoLy;
    //监测点位置
    private TextView monitorLocaTv;
    //监测点名称
    private TextView monitorNameTv;
    //监测状态
    private TextView monitorOnLineTv;
    //监测预警状态
    private TextView monitorStateTv;
    //查看详情按钮
    private Button detailBtn;
    //待办内容
    private TextView remindTv;
    //图层切换
    private ImageView layerImageView;

    /**
     * 地图view
     */
    private MapView mapView;
    /**
     * 地图控制对象
     */
    private AMap aMap;
    /**
     * 行政搜索
     */
    private DistrictSearch districtSearch;
    private static List<Float> yList = new ArrayList<>();
    private static List<String> xRawDatas = new ArrayList<>();
    /**
     * 当前街道办id
     */
    private StreetBean cuurStreet;
    //展示的区id
    private int districtId;
    //展示区数据对象
    private DistrictBean districtBean;
    //地图图层类型
    private int map_type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        districtId = this.getIntent().getIntExtra("districtId", 0);
        map_type = this.getIntent().getIntExtra("map_type", AMap.MAP_TYPE_NORMAL);
        districtBean = UserManage.getInstance().getDistricById(districtId);
        initView();
        initMapView(savedInstanceState);
        initLocation();
        drawInfosOverlay();
        drawDistrict();
    }

    @Override
    public int getLayoutResId() {
        return R.layout.map_view_layout;
    }

    private void initView() {
        monitorLocaTv = (TextView) findViewById(R.id.info_latlng);
        monitorNameTv = (TextView) findViewById(R.id.info_name);
        monitorStateTv = (TextView) findViewById(R.id.info_state);
        monitorOnLineTv = (TextView) findViewById(R.id.info_online);
        layerImageView = findViewById(R.id.info_map_layer);
        remindTv = (TextView) findViewById(R.id.tv_reminder);
        remindTv.setOnClickListener(this);
        layerImageView.setOnClickListener(this);
        detailBtn = (Button) findViewById(R.id.info_information);
        findViewById(R.id.info_information).setOnClickListener(this);
        mMarkerInfoLy = (RelativeLayout) findViewById(R.id.id_marker_info);
        mapView = (MapView) findViewById(R.id.bmapView);
    }

    @Override
    protected void InitActionBar() {
        super.InitActionBar();
        ActionBar actionBar = getSupportActionBar();
        if(actionBar!=null){
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    //初始化地图数据
    private void initMapView(Bundle bundle) {
        mapView.onCreate(bundle);
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        //绘制点的点击事件
        aMap.setOnMarkerClickListener(this);
        aMap.setOnMapClickListener(this);
        aMap.setMapType(map_type);
        districtSearch = new DistrictSearch(this);
    }

    /**
     * 如果有监测点 定位到第一个监测点
     * 没有就定位到龙岗区区政府
     */
    private void initLocation() {
        StreetBean streetBean = UserManage.getInstance().getStreetById(districtId);
        if(streetBean==null){
            return;
        }
        LatLng cenpt = new LatLng(Double.parseDouble(streetBean.getRegionLat()),
                Double.parseDouble(streetBean.getRegionLng()));
        //深汕合作新区特殊处理
        if(("深汕新区").equals(streetBean.getRegionName())){
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(cenpt, 10));
        } else {
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(cenpt, 12));
        }
        if (districtBean == null) {
            return;
        }
        int redCount=0,orangeCount= 0,yellowCount=0;
        //红色预警计数
        for (MonitorBean monitorBean : UserManage.getInstance().getRedLevelMontor()) {
            if (monitorBean.getMonitorArea() != null && monitorBean.getMonitorArea().getParentAreaId() ==
                    districtBean.getDistrict().getDistrictId()) {
                redCount++;
            }
        }
        //橙色预警计数
        for (MonitorBean monitorBean : UserManage.getInstance().getOrangeMontors()) {
            if (monitorBean.getMonitorArea() != null && monitorBean.getMonitorArea().getParentAreaId() ==
                    districtBean.getDistrict().getDistrictId()) {
                orangeCount++;
            }
        }
        //黄色预警计数
        for (MonitorBean monitorBean : UserManage.getInstance().getYellowMontors()) {
            if (monitorBean.getMonitorArea() != null && monitorBean.getMonitorArea().getParentAreaId() ==
                    districtBean.getDistrict().getDistrictId()) {
                yellowCount++;
            }
        }
        if (redCount==0&&orangeCount==0&&yellowCount==0) {
            remindTv.setVisibility(View.GONE);
            return;
        }
        remindTv.setVisibility(View.VISIBLE);
        StringBuilder stringBuilder = new StringBuilder("您管辖的区域有");
        if (redCount!=0) {
            stringBuilder.append(redCount).append("个监测点达到红色报警级别");
        }

        if (orangeCount!=0) {
            if (redCount!=0) {
                stringBuilder.append(";");
            }
            stringBuilder.append(orangeCount).append("个监测点达到橙色预警级别");
        }

        if (yellowCount!=0) {
            if (orangeCount!=0) {
                stringBuilder.append(";");
            }
            stringBuilder.append(yellowCount).append("个监测点达到黄色预警级别");
        }
        stringBuilder.append(",点击查看监详情");
        stringBuilder.append("          ");
        remindTv.setText(stringBuilder.toString());
        remindTv.postDelayed(() -> remindTv.setSelected(true),300);
    }

    /**
     * 绘制观察点
     */
    public void drawInfosOverlay() {
        //当前区下面所有的街道办
        List<StreetBean> streetList = new ArrayList<>();
        for (StreetBean streetBean : UserManage.getInstance().getAllStreetList()) {
            if (streetBean.getParentAreaId() == districtId || streetBean.getRegionAreaId() == districtId) {
                streetList.add(streetBean);
            }
        }
        for (StreetBean bean : streetList) {
            double lat, lng;
            BitmapDescriptor bitmap;
            lat = Double.parseDouble(bean.getRegionLat());
            lng = Double.parseDouble(bean.getRegionLng());
            //街道办状态
            int state = UserManage.getInstance().getStreetState((bean).getRegionAreaId());
            switch (state) {
                default:
                case Constant.WARN_LEVEL_GREEN:
                    bitmap = BitmapDescriptorFactory.fromResource(R.drawable.maker_stree);
                    break;
                case Constant.WARN_LEVEL_YELLOW:
                    bitmap = BitmapDescriptorFactory.fromResource(R.drawable.maker_stree_yu);
                    break;
                case Constant.WARN_LEVEL_ORANGE:
                    bitmap = BitmapDescriptorFactory.fromResource(R.drawable.maker_stree_orange);
                    break;
                case Constant.WARN_LEVEL_RED:
                    bitmap = BitmapDescriptorFactory.fromResource(R.drawable.maker_stree_error);
                    break;
            }
            if ((bean).getAreaLevel() == 2) {
                bitmap = BitmapDescriptorFactory.fromResource(R.drawable.maker_government);
            }
            //经纬度
            LatLng latLng = new LatLng(lat, lng);
            MarkerOptions markerOptions = new MarkerOptions()
                    .position(latLng)
                    .icon(bitmap)
                    .draggable(false);
            String string = bean.getRegionName();
            if(string.lastIndexOf("街道")>=0){
                string = string.substring(0,string.lastIndexOf("街道"));
            }
            TextOptions textOptions = new TextOptions()
                    .position(latLng)
                    .text(string)
                    .fontSize(AppUtils.sp2px(12))
                    .fontColor(Color.DKGRAY);
            aMap.addText(textOptions);
            aMap.addMarker(markerOptions);
        }

    }

    /**
     * 绘制行政区域
     */
    public void drawDistrict() {
        String districtName;
        if (districtBean == null) {
            String regionName = UserManage.getInstance().getStreetById(districtId).getRegionName();
            districtName = regionName.substring(0, regionName.length() - 2);
        } else {
            districtName = districtBean.getDistrict().getDistrictName();
        }

        if("深汕新区".equals(districtName)){
            districtName = "海丰县";
        }

        DistrictSearchQuery query = new DistrictSearchQuery();
        query.setKeywords(districtName);//传入关键字
        query.setShowBoundary(true);//是否返回边界值
        districtSearch.setQuery(query);
        districtSearch.setOnDistrictSearchListener(new DistrictSearch.OnDistrictSearchListener() {
            @Override
            public void onDistrictSearched(DistrictResult districtResult) {
                if (districtResult == null) {
                    return;
                }
                if (districtResult.getAMapException().getErrorCode() != AMapException.CODE_AMAP_SUCCESS) {
                    return;
                }
                if (districtResult.getDistrict().isEmpty()) {
                    return;
                }
                ArrayList<DistrictItem> list = districtResult.getDistrict();
                for (DistrictItem item : list) {
                    //搜索结果过滤掉非深圳市和汕尾市的地区
                    if (item == null||!(CITY_CODE_SHAN.equals(item.getCitycode())||CITY_CODE.equals(item.getCitycode()))) {
                        continue;
                    }
                    //开始绘制
                    new Thread() {
                        public void run() {
                            String[] polyStr = item.districtBoundary();
                            if (polyStr == null || polyStr.length == 0) {
                                return;
                            }
                            for (String str : polyStr) {
                                String[] lat = str.split(";");
                                PolygonOptions polylineOption = new PolygonOptions();
                                boolean isFirst = true;
                                LatLng firstLatLng = null;
                                for (String latstr : lat) {
                                    String[] lats = latstr.split(",");
                                    if (isFirst) {
                                        isFirst = false;
                                        firstLatLng = new LatLng(Double.parseDouble(lats[1]), Double.parseDouble(lats[0]));
                                    }
                                    polylineOption.add(new LatLng(Double.parseDouble(lats[1]), Double.parseDouble(lats[0])));
                                }
                                if (firstLatLng != null) {
                                    polylineOption.add(firstLatLng);
                                }
                                polylineOption.strokeWidth(6)
                                        .strokeColor(Color.parseColor("#FF136014"))
                                        .fillColor(Color.argb(100, 128, 216, 255));
                                aMap.addPolygon(polylineOption);
                            }
                        }
                    }.start();
                }
            }
        });
        districtSearch.searchDistrictAsyn();
    }


    /**
     * 街道办详情
     *
     * @param info
     */
    public void showStreeDetail(StreetBean info) {
        if (info == null) {
            return;
        }
        cuurStreet = info;
        // 设置详细信息布局为可见
        mMarkerInfoLy.setVisibility(View.VISIBLE);
        String location = String.format(getString(R.string.mountain_location), Double.valueOf(info.getRegionLat()), Double.valueOf(info.getRegionLng()));
        monitorLocaTv.setText(location);
        monitorNameTv.setText(String.format(getString(R.string.mountain_name), info.getRegionName()));
        monitorStateTv.setVisibility(View.GONE);
        monitorOnLineTv.setVisibility(View.GONE);
        if (info.getAreaLevel() == 2) {
            detailBtn.setVisibility(View.INVISIBLE);
        } else {
            detailBtn.setVisibility(View.VISIBLE);
        }
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(Double.valueOf(info.getRegionLat()),
                Double.valueOf(info.getRegionLng()))));
    }

    /**
     * @deprecated
     */
    public static List getYList() {
        return yList;
    }

    /**
     * @deprecated
     */
    public static List getXList() {
        return xRawDatas;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.info_information:
                List<MonitorBean> list = UserManage.getInstance().getListMonitorFromStree(cuurStreet);
                if (list.size() > 0) {
                    PointsListDialog dialog = new PointsListDialog(this, list);
                    dialog.show();
                    dialog.setListener((bean) -> {
                        //查看详情
                        Intent intent = new Intent(DistrictMapActivity.this, InformationActivity.class);
                        intent.putExtra("cuurMonitorId", bean.getMonitorPointId());
                        startActivity(intent);
                        if (mMarkerInfoLy != null) {
                            mMarkerInfoLy.setVisibility(View.GONE);
                        }
                    });
                } else {
                    Toast.makeText(this, "没有监测点", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.tv_reminder:
                Intent intent = new Intent(this,WaitActivity.class);
                intent.putExtra("districtId",districtBean.getDistrict().getDistrictId());
                startActivity(intent);
                break;
            case R.id.info_map_layer:
                if(aMap==null){
                    return;
                }
                //地图图层切换
                aMap.setMapType(aMap.getMapType()==AMap.MAP_TYPE_NORMAL?AMap.MAP_TYPE_SATELLITE:AMap.MAP_TYPE_NORMAL);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        mapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }


    @Override
    public boolean onMarkerClick(Marker marker) {
        if(aMap==null){
            return false;
        }
        List<StreetBean> allStreetList = UserManage.getInstance().getAllStreetList();
        LatLng latLng = marker.getPosition();
        StreetBean bean = null;
        for (StreetBean streetBean : allStreetList) {
            if(String.valueOf(latLng.latitude).equals(streetBean.getRegionLat())&&
                    String.valueOf(latLng.longitude).equals(streetBean.getRegionLng())){
                bean = streetBean;
                break;
            }
        }
        if(bean!=null){
            //街道办点击事件
            showStreeDetail(bean);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
            default:
                finish();
                break;
        }
        return true;
    }

    @Override
    public void onMapClick(LatLng latLng) {
        if(mMarkerInfoLy.getVisibility()==View.VISIBLE){
            mMarkerInfoLy.setVisibility(View.GONE);
        }
    }
}
